package org.usmile.algorithms.leetcode.middle;

import java.util.PriorityQueue;
import java.util.Random;

/**
 * 215. 数组中的第K个最大元素
 *
 * 给定整数数组 nums 和整数 k，请返回数组中第 k 个最大的元素。
 * 请注意，你需要找的是数组排序后的第 k 个最大的元素，而不是第 k 个不同的元素。
 * 你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。
 *
 * 示例 1:
 * 输入: [3,2,1,5,6,4], k = 2
 * 输出: 5
 *
 * 示例 2:
 * 输入: [3,2,3,1,2,4,5,5,6], k = 4
 * 输出: 4
 *
 * 提示：
 * 1 <= k <= nums.length <= 105
 * -104 <= nums[i] <= 104
 */
public class _0215 {
}

class _0215_Solution {
    private int k;

    public int findKthLargest(int[] nums, int k) {
        this.k = k;

        quickSort(nums, 0, nums.length - 1);

        return nums[nums.length - k];
    }

    private void quickSort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }

        int p = partition(nums, left, right);
        if (p == nums.length - k) {
            return;
        }

        if (p < nums.length - k) {
            quickSort(nums, p + 1, right);
        } else {
            quickSort(nums, left, p - 1);
        }
    }

    private int partition(int[] nums, int left, int right) {
        int randomIndex = new Random().nextInt(right - left + 1) + left;
        int pivot = nums[randomIndex];
        swap(nums, randomIndex, right);

        int i = left;
        int less = left;
        while (i < right) {
            if (nums[i] < pivot) {
                if (i != less) {
                    swap(nums, i, less);
                }
                less++;
            }
            i++;
        }

        swap(nums, less, right);

        return less;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
    }
}

class _0215_Solution1 {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int num : nums) {
            if (priorityQueue.size() < k) {
                priorityQueue.add(num);
            } else {
                if (num > priorityQueue.peek()) {
                    priorityQueue.poll();
                    priorityQueue.add(num);
                }
            }
        }

        return priorityQueue.peek();
    }
}